package com.cc.ttsreader

import android.Manifest
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.dialog_setting.*
import kotlinx.android.synthetic.main.fragment_text.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.w3c.dom.Text
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import java.lang.Exception
import java.lang.StringBuilder
import java.nio.charset.Charset

const val TTS_DOWNLOAD_URL =
    "http://118.25.73.80:8080/AppCopyRIght/voiceengine.apk"

class MainActivity : AppCompatActivity() {

    var reader: BufferedReader? = null

    var textList = mutableListOf<String>()

    val loadingDialog by lazy {
        ProgressDialog(this)
    }

    @SuppressLint("CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        PermissionFragment().also {
            it.block = {
                if (it) {
                    readText(readOutSide())
                } else {
                    android.app.AlertDialog.Builder(this@MainActivity).setMessage("请在设置中授予存储权限")
                        .show()
                }
            }
            it.check(this)
        }

    }


    private fun readOutSide(): String? {
        var path: String? = try {
            var s: String? = null
            intent.data?.let {
                val cursor = contentResolver.query(
                    it, null,
                    null, null, null, null
                )
                cursor?.run {
                    moveToFirst()
                    s =
                        cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA))
                    close()
                }
            }
            s
        } catch (e: Exception) {
            null
        }
        if (path != null) {
            setCacheFile(path)
        } else {
            path = getLastFilePath()
        }
        return path
    }

    var fileName = ""
    private fun readText(path: String?) {
        if (path?.isNotBlank() == true) {
            path.let {
                val file = File(path)
                reader =
                    BufferedReader(InputStreamReader(FileInputStream(file), Charset.forName("GBK")))
                fileName = file.name
            }
        }
        if (reader == null) {
            AlertDialog.Builder(this)
                .setMessage("请从文件管理器打开文本文件，选择使用${getString(R.string.app_name)}打开")
                .setPositiveButton("确定", null).create().show()
            return
        }
        loadingDialog.show()
        GlobalScope.launch {
            val pageLineCount = 50
            val ts = reader!!.readLines()
            val lineCount = ts.size / pageLineCount
            var startIndex = 0
            var endIndex = lineCount
            for (i in 0 until lineCount) {
                startIndex = i * pageLineCount
                if (i == lineCount - 1) {
                    endIndex = ts.size - 1
                } else {
                    endIndex = (i + 1) * pageLineCount
                }
                textList.add(ts.subList(startIndex, endIndex).toString())
            }
            withContext(Dispatchers.Main)
            {
                initVp()
                loadingDialog.dismiss()
            }
        }
        supportActionBar?.title = "$fileName 第1页"
    }

    private fun initVp() {
        vp.adapter = object : FragmentPagerAdapter(
            supportFragmentManager,
            FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getItem(position: Int): Fragment {
                return TextFragment().also {
                    it.arguments = Bundle().also { it.putString("text", textList.get(position)) }
                }
            }

            override fun getCount(): Int {
                return textList.size
            }
        }
        vp.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                supportActionBar?.title = "$fileName 第${position + 1}页"
                setLastPosition(position)
            }
        })
        val position = getLastPosition()
        setPosition(position)
    }

    fun setPosition(position: Int) {
        if (position == 0) {
            vp.setCurrentItem(1)
        }
        if (position - 1 >= textList.size) {
            Toast.makeText(this, "共${textList.size}页，所选页面超过最大页数", Toast.LENGTH_LONG).show()
            return
        } else if (position == -1) {
            vp.setCurrentItem(textList.size - 1)
            return
        }
        vp.setCurrentItem(position - 1)
    }
}

var tts: TextToSpeechHelper? = null

class TextFragment : Fragment() {
    val bottmSheetDialg by lazy {
        BottomSheetDialog(context!!).also { d ->
            d.setContentView(R.layout.dialog_setting)
            d.btnTts.setOnClickListener {
                tts?.speech(tv.text) {}
                context!!.startService(
                    Intent(
                        context!!,
                        TTSServer::class.java
                    ).also { it.putExtra("text", tv.text) })
                d.dismiss()
            }
            d.btnGo.setOnClickListener {
                if (d.etGo.text.isNotBlank()) {
                    (activity as MainActivity).setPosition(d.etGo.text.toString().toInt())
                }
            }
            d.btnGoFirst.setOnClickListener {
                (activity as MainActivity).setPosition(0)
                d.dismiss()
            }
            d.btnGoEnd.setOnClickListener {
                (activity as MainActivity).setPosition(-1)
                d.dismiss()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        tts
        return inflater.inflate(R.layout.fragment_text, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (tts == null) {
            tts = TextToSpeechHelper(context!!) {
                if (!it) {
                    AlertDialog.Builder(context!!).setMessage("未安装语音引擎或语言不支持，请下载安装并启用中文语音引擎")
                        .setPositiveButton(
                            "已安装去设置"
                        ) { dialog, which ->
                            startActivity(Intent("com.android.settings.TTS_SETTINGS"));
                        }
                        .setNegativeButton("去下载", DialogInterface.OnClickListener { dialog, which ->
                            val intent = Intent()
                            intent.action = "android.intent.action.VIEW"
                            val content_url = Uri.parse(TTS_DOWNLOAD_URL)
                            intent.data = content_url
                            startActivity(intent)
                        }).show()
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val text = arguments?.getString("text")
        tv.text = text
        tv.setOnClickListener {
            bottmSheetDialg.show()
        }
    }
}
